package com.docker.test.docker;

import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;


@Component
@RabbitListener(queues = "TestDirectQueue")
public class DirectReceiver {
    private static Logger logger = LoggerFactory.getLogger(DirectReceiver.class);
    private static int numSize = 100;
    public CountDownLatch intSize = new CountDownLatch(100);

    @RabbitHandler
    public void process(String testMessage, Channel channel, Message message) {
//        System.out.println("DirectReceiver消费者收到消息  : " + testMessage.toString());
        synchronized (this){
            numSize--;
            logger.info("numSize:【{}】",numSize);
        }


        ackMethod(channel,message);
    }

    public void ackMethod(Channel channel, Message message){
        try {
            //告诉服务器收到这条消息 已经被我消费了 可以在队列删掉 这样以后就不会再发了 否则消息服务器以为这条消息没处理掉 后续还会在发
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
//            System.out.println("receiver success");
        } catch (IOException e) {
            e.printStackTrace();
            //丢弃这条消息
            //channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,false);
//            System.out.println("receiver fail");
        }
    }
}
